<template>
  <div>
     <img src="../../img/dl.png" alt="" class="img">
    <van-form @submit.prevent="register">
  <van-cell-group inset>
    <van-field
      v-model="username"
      name="用户名"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <span v-if="!isUsernameValid" style="color: red;">用户名不合法</span>
    <van-field
      v-model="confirmPassword"
      type="password"
      name="再次输入密码"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
      <span v-if="password.value!== confirmPassword.value" style="color: red;">密码不一致</span>
      <span v-if="!isPasswordValid" style="color: red;">密码不合法</span>
    <van-field
      v-model="password"
      type="password"
      name="密码"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
      <span v-if="!isPasswordValid" style="color: red;">密码不合法</span>
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit" :disabled="!isFormValid">
      注册
    </van-button>
  </div>
</van-form>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const username = ref('');
const password = ref('');
const confirmPassword = ref('');
const router = useRouter();

const usernameRegex = /^[a-zA-Z0-9_]{4,20}$/;
const passwordRegex = /^[a-zA-Z0-9_]{6,20}$/;

const isUsernameValid = computed(() => usernameRegex.test(username.value));
const isPasswordValid = computed(() => passwordRegex.test(password.value));
const isFormValid = computed(() => isUsernameValid.value && isPasswordValid.value && password.value === confirmPassword.value);

const register = async () => {
  if (!isFormValid.value) return;
  try {
    const response = await axios.post('/api/register', {
      username: username.value,
      password: password.value
    });
    if (response.data.success) {
      // 注册成功，跳转到登录页面
      router.push('/login');
    } else {
      console.error('注册失败:', response.data.message);
    }
  } catch (error) {
    console.error('注册错误:', error);
  }
};
</script>

<style>
.img{
  width: 100%;
  height: 300px;
}
</style>